package com.ksd.quartz.util;

import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class FileUtil {
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
	public static String readByLine(String filePath) {
		if (filePath == null || filePath.isEmpty()) {
			return null;
		}
		String readData = null;
		StringBuilder strBuilder = new StringBuilder();
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader bufferReader = new BufferedReader(fileReader);
			while (true) {
				readData = bufferReader.readLine();
				if (readData == null)
					break;
				strBuilder.append(readData);
			}
			bufferReader.close();
			fileReader.close();
			readData = strBuilder.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return readData;
	}

	public static byte[] readFile(String filePath) {
		if (filePath == null || filePath.isEmpty()) {
			return null;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			return null;
		}
		byte[] readBuffer = new byte[8192000];
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			int readLength = fis.read(readBuffer);
			fis.close();

			byte[] readData = new byte[readLength];
			System.arraycopy(readBuffer, 0, readData, 0, readLength);
			return readData;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static String startsWithHttpByIndex(String filePath) {
		if (filePath.startsWith("http") || filePath.startsWith("https")) {
			int indexOf = filePath.lastIndexOf(":");
			filePath = filePath.substring(indexOf);
			indexOf = filePath.indexOf("/");
			filePath = filePath.substring(indexOf);
			System.out.println("切割处理之后的文件路径==>" + filePath);
			return filePath.trim();
		}else {
			return filePath.trim();
		}
	}

	public static byte[] readFile(InputStream is) throws Exception {
		byte[] dateByte = new byte[10240000];
		byte[] dataTemp = new byte[10240];
		int len = 0;
		int totalLen = 0;
		while ((len = is.read(dataTemp)) > 0) {
			System.arraycopy(dataTemp, 0, dateByte, totalLen, len);
			totalLen += len;
		}

		byte[] recvData = new byte[totalLen];
		System.arraycopy(dateByte, 0, recvData, 0, totalLen);
		return recvData;
	}
	
	public static String read(InputStream is) {
		try {
			return new String(readFile(is), "utf-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static boolean writeFile(String filePath, String data) {
		File fout = new File(filePath);
		try {
			FileOutputStream fos = new FileOutputStream(fout, true);
			fos.write(data.getBytes("utf-8"));

			fos.close();

			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public static boolean writeFile(String filePath, byte[] data) {
		File fout = new File(filePath);
		try {
			FileOutputStream fos = new FileOutputStream(fout, true);
			fos.write(data);

			fos.close();

			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public static void readToWrite(String sourcePath,String newFilePath,String updateJarPath) {
		
		File sourceFile = new File(sourcePath);
		File newShellFile = new File(newFilePath);
		if (!newShellFile.exists()) {
			try {
				newShellFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		BufferedReader br = null;
		FileOutputStream fo = null;
		try {
			br = new BufferedReader(new FileReader(sourceFile));
			fo = new FileOutputStream(newShellFile);
			String readLength = null;
			while((readLength = br.readLine())!= null) {
				System.out.println("readLine: "+readLength);
				if (readLength.startsWith("mv changeOldFilePath")) {
					//修改原项目jar包名称做备份
					String yYYY_MM_DD_HH_MM_SS = DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
					String temp = "mv "+ PlayControlConfig.getJarPath()+"playcontrol-admin.jar "+PlayControlConfig.getJarPath()+"playcontrol-admin"+yYYY_MM_DD_HH_MM_SS+".jar";
					logger.info("temp："+temp);
					fo.write(temp.getBytes());
					fo.write("\n".getBytes());
				}else if (readLength.startsWith("cp changeNewFilePath")) {
					//将升级需要的jar包，移动至指定位置，并修改为原oldFile文件名称。
					String temp = "cp "+ updateJarPath +" "+PlayControlConfig.getJarPath()+"playcontrol-admin.jar";
					logger.info("temp："+temp);
					fo.write(temp.getBytes());
					fo.write("\n".getBytes());
				}else if (readLength.startsWith("java")) {
					//启动指定jar包（最新上传的jar包）
					String temp = "java -jar "+PlayControlConfig.getJarPath()+"playcontrol-admin.jar"+" &";
					logger.info("temp："+temp);
					fo.write(temp.getBytes());
					fo.write("\n".getBytes());
				}else{
					fo.write(readLength.getBytes());
					fo.write("\n".getBytes());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}finally {
			if (fo != null) {
				try {
					fo.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("fo关闭");
			}
			if (br != null) {
				try {
					br.close();
					System.out.println("br关闭");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
	}

	public static void readToWriteVue(String sourcePath, String newFilePath, String updateVuePath) {
		File sourceFile = new File(sourcePath);
		File newShellFile = new File(newFilePath);

		// 确保目标目录存在
		if (newShellFile.getParentFile() != null && !newShellFile.getParentFile().exists()) {
			newShellFile.getParentFile().mkdirs();
		}

		if (!newShellFile.exists()) {
			try {
				newShellFile.createNewFile();
			} catch (IOException e) {
				logger.error("创建新文件失败: " + newFilePath, e);
				return; // 创建文件失败则直接返回
			}
		}

		// 使用try-with-resources自动关闭资源
		try (BufferedReader br = new BufferedReader(new FileReader(sourceFile));
			 FileOutputStream fo = new FileOutputStream(newShellFile)) {

			String readLine;
			String vuePath = PlayControlConfig.getVuePath();
			// 确保路径以文件分隔符结尾
			if (!vuePath.endsWith(File.separator)) {
				vuePath += File.separator;
			}

			while ((readLine = br.readLine()) != null) {
				System.out.println("readLine: " + readLine);

				if (readLine.startsWith("mv changeOldFilePath")) {
					// 修改原项目dist.zip包名称做备份
					String timestamp = DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
					String temp = String.format("mv %sdist.zip %sdist%s.zip",
							vuePath, vuePath, timestamp);
					logger.info("生成备份命令: " + temp);
					fo.write(temp.getBytes());
					fo.write("\n".getBytes());
				}
				else if (readLine.startsWith("cp changeNewFilePath")) {
					// 确保updateVuePath是绝对路径或正确的相对路径
					File updateFile = new File(updateVuePath);
					String updateFilePath = updateFile.getAbsolutePath();

					// 将升级需要的dist包移动至指定位置
					String temp = String.format("cp %s %sdist.zip",
							updateFilePath, vuePath);
					logger.info("生成移动命令: " + temp);
					fo.write(temp.getBytes());
					fo.write("\n".getBytes());
				}
				else {
					fo.write(readLine.getBytes());
					fo.write("\n".getBytes());
					logger.info("其他执行命令: " + readLine);
				}
			}
		} catch (Exception e) {
			logger.error("处理文件时发生错误", e);
		}
	}
//	public static void readToWriteVue(String sourcePath,String newFilePath,String updateVuePath) {
//
//		File sourceFile = new File(sourcePath);
//		File newShellFile = new File(newFilePath);
//		if (!newShellFile.exists()) {
//			try {
//				newShellFile.createNewFile();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		BufferedReader br = null;
//		FileOutputStream fo = null;
//		try {
//			br = new BufferedReader(new FileReader(sourceFile));
//			fo = new FileOutputStream(newShellFile);
//			String readLength = null;
//			while((readLength = br.readLine())!= null) {
//				System.out.println("readLine: "+readLength);
//				if (readLength.startsWith("mv changeOldFilePath")) {
//					//修改原项目jar包名称做备份
//					String yYYY_MM_DD_HH_MM_SS = DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
//					String temp = "mv "+ PlayControlConfig.getVuePath()+"dist.zip "+PlayControlConfig.getVuePath()+"dist"+yYYY_MM_DD_HH_MM_SS+".zip";
//					logger.info("temp："+temp);
//					fo.write(temp.getBytes());
//					fo.write("\n".getBytes());
//				}else if (readLength.startsWith("mv changeNewFilePath")) {
//					//将升级需要的jar包，移动至指定位置，并修改为原oldFile文件名称。
//					String temp = "mv "+ updateVuePath +" "+PlayControlConfig.getVuePath()+"dist.zip";
//					logger.info("temp："+temp);
//					fo.write(temp.getBytes());
//					fo.write("\n".getBytes());
//				}else{
//					fo.write(readLength.getBytes());
//					fo.write("\n".getBytes());
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.error(e.getMessage());
//		}finally {
//			if (fo != null) {
//				try {
//					fo.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				System.out.println("fo关闭");
//			}
//			if (br != null) {
//				try {
//					br.close();
//					System.out.println("br关闭");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//
//	}
	
	public static void main(String args[]) throws IOException {
		
		String dataPath = "/hdsuifh/hsduifd/fhuisfsdf/udrmclient.jar";
//		String filePath = "C:\\Users\\wuyun\\Desktop\\升级压缩包\\systemUpgrade_h.sh";
		String filePath = "C:\\Users\\wuyun\\Desktop\\新建文件夹 (2)\\新建文本文档.txt";
		String systemFilePath = "C:\\Users\\wuyun\\Desktop\\新建文件夹 (2)\\新建文本文档2.txt";
		
		String yYYY_MM_DD_HH_MM_SS = DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
		System.out.println(yYYY_MM_DD_HH_MM_SS);
	}	
	
    public static void bufferReaderTest(String filePath) {
    	try {
        	BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = bufferedReader.readLine())  != null) {
                // 处理每一行数据 .....
            	System.out.println(line);
            	System.out.println("jiosdjfisdf");
            }
            bufferedReader.close();
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    
    
    public static void readFileTemp(String filePath)  {
    	//BufferedReader是可以按行读取文件

    	try {
	    	FileInputStream inputStream = new FileInputStream(filePath);
	    	BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
				
			String str;
			while((str = bufferedReader.readLine()) != null){
				System.out.println(str);
			}
			bufferedReader.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

	
}